package dubbo.learn.core.config.parser;

import dubbo.learn.core.component.ExportServicePublishBeanPostProcessor;
import dubbo.learn.core.component.export.ExportService;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.PropertyPathFactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class ExportServiceBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
    private static final String INTERFACE = "interface";

    private static final String EXPORT_SERVICE_FULL_NAME = "exportServiceFullName";

    private static final String EXPORT_SERVICE_POST_PROCESSOR = "ExportServicePublishBeanPostProcessor";


    @Override
    protected Class<?> getBeanClass(Element element) {
        return ExportService.class;
    }

    @Override
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
        String remoteReferenceName = element.getAttribute(INTERFACE);

        builder.addPropertyValue(EXPORT_SERVICE_FULL_NAME, remoteReferenceName);

        BeanDefinitionRegistry registry = parserContext.getRegistry();
        boolean exportServicePublishBeanPostProcessor = registry.containsBeanDefinition(EXPORT_SERVICE_POST_PROCESSOR);
        if (exportServicePublishBeanPostProcessor) {
            return;
        }

        registry.registerBeanDefinition(EXPORT_SERVICE_POST_PROCESSOR, createBeanDefinition());
    }

    protected RootBeanDefinition createBeanDefinition() {
        RootBeanDefinition beanDefinition = new RootBeanDefinition(ExportServicePublishBeanPostProcessor.class);
        beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
        beanDefinition.setSynthetic(true);
        return beanDefinition;
    }


    @Override
    protected boolean shouldGenerateIdAsFallback() {
        return true;
    }

}
